# /usr/bin/python3
# _*_ coding : utf-8 _*_
import random as rand
import time
from pynput import keyboard as kb
from pynput.keyboard import Controller as key_col
from pynput.keyboard import Key as ky
from pynput.mouse import Button, Controller
import datetime
import threading

lis = [u'#签到', u'#打卡']
lis1 = ['鱼子酱', '大酱汤', '炒乌冬', '乌冬面', '醋饭', '鲷鱼烧', '拉面', '海鲜汤', '牛尾汤', '橙醋蟹',
        '海胆汤', '炒牡蛎', '大阪烧', '春卷', '泡菜烧', '鸡肉串', '铜锣烧', '荞麦面', '鳗鱼饭', '苹果饼',
        '蒙多排骨', '奥恩汤', '薇恩豆腐', '炸发条', '安尼鱼', '佐伊饺子', '芮尔饼', '瑞兹煮', '扎克烧', '卡兹克锅', '璐璐烧麦', '五郎红肠', '叔又饿了',
        '奶酪饼', '阿富汗披萨', '玉子烧', '糖醋排骨', '明太鱼', '鳕鱼烧', '五花肉', '章鱼烧', '西京烧', '麻婆豆腐',
        '担担面', '里脊', '牛霖肉', '三文鱼', '酒蒸蛤蜊', '关东煮', '寿喜锅', '三明治', '蛋包饭', '牛肉饭', '石狩锅',
        '昆布', '海苔', '酱汁', '水饺', '饺子', '煎饺', '蒸饺', '酱油拌面', '牛油果', '牛腩', '牛肚', '牛肝', '鸡蛋烧',
        '鱿鱼汤', '鲤鱼汤', '乌贼面', '寿司', '冷面', '炒年糕', '安康鱼', '纳豆饭', '油泼面', '山葵盖饭', '蚬汤', '蚬子面',
        '生姜烧', '鳜鱼', '蒜蓉汤', '鲑鱼', '杏鲍菇', '鲍鱼', '味噌汤', '烤肉', '炸鸡块', '羊排', '番茄炒蛋', '肝盖饭',
        '信玄袋', '鲔鱼汤', '喜知次', '龙虾', '肉串', '鸡蛋卷', '大福', '牛筋', '梅子酒', '线鱼脊', '云吞面', '刺鲳鱼',
        '虾肉山芋', '汉堡肉', '番茄意面', '排骨面', '咖喱饭', '咖喱牛肉', '蕃茄豆腐', '秋刀鱼', '什锦面', '鱼生碎',
        '葱炒肉', '熏肠', '沙丁鱼', '什锦拌', '花蛤', '糯米饭', '鸡肉春卷', '炒培根', '红糟排骨', '黑炒饭', '麻辣汤',
        '竹荚鱼', '玉米饼', '腊肉', '爆羊肉', '绿麻豆腐', '烧虾仁', '鱼丸面', '煲仔饭', '肠炒面', '青花鱼', '横膈膜肉',
        '麻婆凉面', '肉汁乌冬', '奶油海鲜', '薄切牛肉', '炸火腿', '炸酱面', '乌鱼子', '银鲑', '咖喱炒面', '葱花蛋',
        '仁当牛', '鸡酱烧', '蕈菇海螺', '炖牛舌', '蟹面', '炒酱面', '烘肉卷', '鸡肉锅', '马头鱼', '方头鱼', '菌菇汤',
        '寿喜烧', '小圆', '甜点', '牛舌', '泡菜鱼', '牛肉煮', '盐渍鲭鱼意面', '虾仁', '海鲜饭', '牛肉饭', '鲣鱼']
lis2 = [u',', '啊', '不错']

semaphore = threading.Semaphore(0)
item = 0

class MyException(KeyboardInterrupt):
    def __init__(self, key):
        super(self).__init__()
        self.key = key

    # 'Program interrupted by user.'
    def with_traceback(self,):
        self.with_traceback()


def keyboard_input(string):
    # control the keyboard
    keyboard = key_col()
    # keyboard input text
    keyboard.type(string)
    time.sleep(0.5)
    # Press and release enter
    keyboard.press(ky.enter)
    keyboard.release(ky.enter)


def mouse_click():
    # control mouse
    mouse = Controller()
    # set absolute position
    # mouse.position = (1398, 769)
    # mouse.position = (1394, 764)
    mouse.press(Button.left)
    # print(mouse.position)
    mouse.release(Button.left)


def time_count(interval=20):
    # t1 = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    t1 = datetime.datetime.now().strftime("%H:%M:%S")
    print('current time is [{}]'.format(t1))
    # t2 = (datetime.datetime.now()+datetime.timedelta(minutes=5)).strftime("%Y-%m-%d %H:%M:%S")
    t2 = (datetime.datetime.now() +
          datetime.timedelta(minutes=interval)).strftime("%H:%M:%S")
    print('\n[{}] woulde be incoming.'.format(t2))


def on_press(key):
    if key == kb.Key.esc:
        raise MyException(key)

# def findwindowfrommouse():
#     mouse_click()
#     hw = win32gui.WindowFromPoint(win32api.GetCursorPos())
#     # print('hw', hw)
#     # print('hex(hw)', hex(hw))
#     title = win32gui.GetWindowText(hw)
#     # print(title)
#     return hw


def kep_press_combo(num:str):
    # control the keyboard
    keyboard = key_col()
    # keyboard input text
    # keyboard.type(string)
    # Press and release enter
    # keyboard.press(ky.enter)
    # keyboard.release(ky.enter)
    with keyboard.pressed(ky.ctrl):
    # with keyboard.pressed(ky.alt):
        keyboard.press(num)
        keyboard.release(num)
        pass

    keyboard.release(ky.ctrl)
    # keyboard.release(ky.alt)
    # print("ctrl+2 has been pressed!")


def main(number, string, iinterval=20):
    """
        :number: times of loop
        :iinterval: interval of executing 
    """
    # with kb.Listener(
    #     on_press=on_press) as listener:
    #     try:
    #         listener.join()
    #     except MyException as e:
    #         print('{0} was pressed'.format(e.args[0]))
    #(1398, 769)
    #(1398, 769)
    # (1396, 774)
    # (1396, 774)
    # 签到
    print('----start----')
    time.sleep(5)
    try:
        for i in range(number):
            # count of record input
            # time.sleep(60 * iinterval  + 5 + i)
            # if((i & 1) == 0):
            kep_press_combo()
            time.sleep(1)
            # findwindowfrommouse()
            mouse_click()
            keyboard_input(lis1[rand.randint(0, number-1)] + ',')
            time_count(iinterval)
            # mouse_click()
            # time.sleep(12 + i)
            time.sleep(rand.randint(6, 10))
            keyboard_input(lis[0])
            # mouse_click()
            print('[{0}] is finished -- [{1}] left'.format(i, number - i))
            # time.sleep(6 + i)
            # keyboard_input(lis1[rand.randint(0, number-1)] + ',')
            # mouse_click()
            time.sleep(60 * iinterval + rand.randint(3, 6))
            # time.sleep(60 * 20 + 5 + i)
            # else:
            #     keyboard_input(lis1[rand.randint(0, number-1)] + ',')
            #     time_count(iinterval)
            #     # mouse_click()
            #     # time.sleep(10 + i)
            #     time.sleep(rand.randint(8, 12))
            #     keyboard_input(lis[1])
            #     # mouse_click()
            #     print('[{0}] is finished -- [{1}] left'.format(i, number - i))
            #     time.sleep(6 + i)
            #     keyboard_input(lis1[rand.randint(0, number-1)] + ',')
            #     # mouse_click()
            #     time.sleep(60 * iinterval + 3 + i)
    except Exception as e:
        print('{0} was pressed'.format(e.args[0]))


def main1(number, string):
    lis = ['#签到', '#打卡']
    lis1 = ['糖醋排骨', '明太鱼', '鳕鱼烧', '五花肉', '章鱼烧', '西京烧', '麻婆豆腐', '担担面', '里脊',
            '牛霖肉', '三文鱼', '酒蒸蛤蜊', '关东煮', '寿喜锅', '三明治', '蛋包饭', '牛肉饭', '寿喜烧', '甜点',
            '牛舌', '泡菜鱼', '牛肉煮', '盐渍鲭鱼意面',]
    # lis2 = [',', '啊','不错']
    # with kb.Listener(
    #     on_press=on_press) as listener:
    #     try:
    #         listener.join()
    #     except MyException as e:
    #         print('{0} was pressed'.format(e.args[0]))

    print('----start----')
    time.sleep(5)
    for i in range(number):
        # count of record input
        # time.sleep(60 * 20  + 5 + i)
        if((i & 1) == 0):
            keyboard_input(lis1[rand.randint(0, number-1)] + ',')
            mouse_click()
            time.sleep(12 + i)
            keyboard_input(lis[0])
            mouse_click()
            time.sleep(60 * 20 + 5 + i)
        else:
            keyboard_input(lis1[rand.randint(0, number-1)] + ',,')
            mouse_click()
            time.sleep(10 + i)
            keyboard_input(lis[1])
            mouse_click()
            time.sleep(60 * 20 + 3 + i)
    print('----stop----')

def fun_daka(number, string, iinterval=20,keyno:str = '2'):
    """
    :param number: times of loop
    :param iinterval: interval of executing 
    """
    # with kb.Listener(
    #     on_press=on_press) as listener:
    #     try:
    #         listener.join()
    #     except MyException as e:
    #         print('{0} was pressed'.format(e.args[0]))
    #(1398, 769)
    #(1398, 769)
    # (1396, 774)
    # (1396, 774)
    # 签到
    print('----start----')
    time.sleep(2)
    try:
        # for i in range(number):
            # count of record input
            # time.sleep(60 * iinterval  + 5 + i)
            # if((i & 1) == 0):
        kep_press_combo(keyno)
        time.sleep(1)
        # findwindowfrommouse()
        mouse_click()
        # keyboard_input(lis1[rand.randint(0, number-1)] + ',')
        time_count(iinterval)
        # mouse_click()
        # time.sleep(12 + i)
        # time.sleep(rand.randint(6, 10))
        keyboard_input(lis[1])
        # time.sleep(2)
        # keyboard_input(lis2[0])
        time.sleep(1)
        # mouse_click()
        # print('[{0}] is finished -- [{1}] left'.format(i, number - i))
            # time.sleep(6 + i)
            # keyboard_input(lis1[rand.randint(0, number-1)] + ',')
            # mouse_click()
            # time.sleep(60 * iinterval + rand.randint(3, 6))
            # time.sleep(60 * iinterval + 3)
            # time.sleep(60 * 20 + 5 + i)
            # else:
            #     keyboard_input(lis1[rand.randint(0, number-1)] + ',')
            #     time_count(iinterval)
            #     # mouse_click()
            #     # time.sleep(10 + i)
            #     time.sleep(rand.randint(8, 12))
            #     keyboard_input(lis[1])
            #     # mouse_click()
            #     print('[{0}] is finished -- [{1}] left'.format(i, number - i))
            #     time.sleep(6 + i)
            #     keyboard_input(lis1[rand.randint(0, number-1)] + ',')
            #     # mouse_click()
            #     time.sleep(60 * iinterval + 3 + i)
    except Exception as e:
        print('{0} was pressed'.format(e.args[0]))

def confunc2(convariable, number:int, string:str = "___fun2_test___", iinterval:int =30):
    """
    :param convariable: threading.Condition
    :param number: int -times of loop
    :param iinterval: int -interval of executing 
    """
    # with kb.Listener(
    #     on_press=on_press) as listener:
    #     try:
    #         listener.join()
    #     except MyException as e:
    #         print('{0} was pressed'.format(e.args[0]))
    #(1398, 769)
    #(1398, 769)
    # (1396, 774)
    # (1396, 774)
    # 签到
    print('---1_start----')
    time.sleep(2)
    try:
        for i in range(number):
            # count of record input
            # time.sleep(60 * iinterval  + 5 + i)
            # if((i & 1) == 0):
            if convariable.acquire():
                kep_press_combo('2')
                time.sleep(1)
                # findwindowfrommouse()
                mouse_click()
                time.sleep(1)
                # keyboard_input(lis1[rand.randint(0, number-1)] + ',')
                # keyboard_input(rand.choice(lis1) + ',')
                time_count(iinterval)
                # mouse_click()
                # time.sleep(12 + i)
                time.sleep(4)
                # time.sleep(rand.randint(4, 6))
                keyboard_input(lis[1])
                
                # mouse_click()
                print('[{0}] is finished -- [{1}] left'.format(i, number - i))
                # time.sleep(6 + i)
                # keyboard_input(lis1[rand.randint(0, number-1)] + ',')
                # mouse_click()
                convariable.notify()
                convariable.wait()
                # time.sleep(2)
                # time.sleep(60 * iinterval + rand.randint(3, 5))
                time.sleep(60 * iinterval + 3)
            else:
                time.sleep(3)
                continue
                # time.sleep(60 * 20 + 5 + i)
                # else:
                #     keyboard_input(lis1[rand.randint(0, number-1)] + ',')
                #     time_count(iinterval)
                #     # mouse_click()
                #     # time.sleep(10 + i)
                #     time.sleep(rand.randint(8, 12))
                #     keyboard_input(lis[1])
                #     # mouse_click()
                #     print('[{0}] is finished -- [{1}] left'.format(i, number - i))
                #     time.sleep(6 + i)
                #     keyboard_input(lis1[rand.randint(0, number-1)] + ',')
                #     # mouse_click()
                #     time.sleep(60 * iinterval + 3 + i)
        convariable.release()        
    except Exception as e:
        print('{0} was pressed'.format(e.args[0]))
        convariable.release()

def confunc3(convariable, number:int, string:str = "___fun3_test___", iinterval:int =30):
    """
    :param convariable: threading.Condition
    :param number: int -times of loop
    :param iinterval: int -interval of executing 
    """
    # with kb.Listener(
    #     on_press=on_press) as listener:
    #     try:
    #         listener.join()
    #     except MyException as e:
    #         print('{0} was pressed'.format(e.args[0]))
    #(1398, 769)
    #(1398, 769)
    # (1396, 774)
    # (1396, 774)
    # 签到
    print('---2_start----')
    time.sleep(5)
    try:
        for i in range(number):
            # count of record input
            # time.sleep(60 * iinterval  + 5 + i)
            # if((i & 1) == 0):
            if convariable.acquire():
                kep_press_combo('3')
                time.sleep(1)
                # findwindowfrommouse()
                mouse_click()
                time.sleep(1)
                # keyboard_input(lis1[rand.randint(0, number-1)] + ',')
                # keyboard_input(rand.choice(lis1) + ',')
                time_count(iinterval)
                # mouse_click()
                # time.sleep(12 + i)
                # time.sleep(rand.randint(4, 6))
                keyboard_input(lis[1])
                # mouse_click()
                print('[{0}] is finished -- [{1}] left'.format(i, number - i))
                # time.sleep(6 + i)
                # keyboard_input(lis1[rand.randint(0, number-1)] + ',')
                # mouse_click()
                convariable.notify()
                convariable.wait()
                time.sleep(4)
                # time.sleep(60 * iinterval + rand.randint(3, 6))
                # time.sleep(60 * iinterval + rand.randint(6, 7))
                time.sleep(60 * iinterval + 6)
            else:
                time.sleep(4)
                continue
                # time.sleep(60 * 20 + 5 + i)
                # else:
                #     keyboard_input(lis1[rand.randint(0, number-1)] + ',')
                #     time_count(iinterval)
                #     # mouse_click()
                #     # time.sleep(10 + i)
                #     time.sleep(rand.randint(8, 12))
                #     keyboard_input(lis[1])
                #     # mouse_click()
                #     print('[{0}] is finished -- [{1}] left'.format(i, number - i))
                #     time.sleep(6 + i)
                #     keyboard_input(lis1[rand.randint(0, number-1)] + ',')
                #     # mouse_click()
                #     time.sleep(60 * iinterval + 3 + i)
        convariable.release()    
    except Exception as e:
        print('{0} was pressed'.format(e.args[0]))
        convariable.release()

def fun_print2(convariable, num:int, string:str="__testing__", iinterval:int=20):   
    for i in range(num):
        if convariable.acquire():
            print("i:[{}] -- interval[{}]".format(i, iinterval))
            fun_daka(1, "" , iinterval, '2')
            convariable.notify()
        convariable.wait()
        time.sleep(60 * iinterval)
    convariable.release()    

def fun_print3(convariable, num:int, string:str="__testing__", iinterval:int=30):    
    time.sleep(8)
    for t in range(num):
        if convariable.acquire():
            print("t:[{}] -- interval[{}]".format(t, iinterval))
            fun_daka(1, "" , iinterval, '3')
            convariable.notify()
        convariable.wait()
        time.sleep(2)
        time.sleep(60 * iinterval)
    convariable.release()        

def run_pool():
    convariable = threading.Condition()

    # t_args = [(20, 2), (20, 3)]
    # t1 = Thread(target=fun_print2, args=t_args[0])
    # t2 = Thread(target=fun_print3, args=t_args[1])
    t1 = threading.Thread(target=confunc2, args=(convariable, 40, 20))
    t2 = threading.Thread(target=confunc3, args=(convariable, 40, 30)) 

    t1.start()
    time.sleep(45)
    t2.start()
    t1.join()
    t2.join()

    convariable.release()

def run_pool2():
    convariable = threading.Condition()

    t_args = [(20, 2), (20, 3)]
    # t1 = Thread(target=fun_print2, args=t_args[0])
    # t2 = Thread(target=fun_print3, args=t_args[1])
    t1 = threading.Thread(target=fun_print2, args=(convariable, 40, '', 30))
    t2 = threading.Thread(target=fun_print3, args=(convariable, 40, '', 30))

    t1.start()
    time.sleep(10)
    t2.start()
    t1.join()
    t2.join()
    convariable.release()

def consumer(num:int = 20, iinterval:int = 30, keynum:str = '2'):
    """
    consumer function
    """
    # time.sleep(8)
    for i in range(num):
        time.sleep(8)
        print("---wait for producer running---")
        # acquire resouces, semaphore is zero,
        # wait for semaphore be released.
        semaphore.acquire()
        print("cser-current thread name is %s" %
              threading.current_thread().name)
        # print("wait-6-seconds---consumer finish---No.:[%s]" % item)
        fun_daka(1, "" , iinterval, keynum)
        time.sleep(8)
        time.sleep(60 * iinterval + 4)


def producer(num:int = 20, iinterval:int = 20):
    """producer function"""
    # global item
    for i in range(num):
        time.sleep(2)

        # item = random.randint(0, 100)
        # item += 1
        print("pro-current thread name is %s" %
              threading.current_thread().name)
        # print("wait-4-seconds-producer running No.:[%s]" % item)
        # fun_daka(1, "" , iinterval, '2')
        semaphore.release()
        time.sleep(60 * iinterval)

def run_semaphore():
    dict1 = {"num": 40, "iinterval":20, "keynum": '2'}
    dict2 = {"num": 40, "iinterval":30, "keynum": '3'}
    t1 = threading.Thread(target=producer, args=(40, 20,))
    t2 = threading.Thread(target=consumer, kwargs=dict1)
    t3 = threading.Thread(target=producer, args=(40, 30,))
    t4 = threading.Thread(target=consumer, kwargs=dict2)
    
    t1.start()
    # time.sleep(32)
    t2.start()
    time.sleep(32)
    t3.start()
    t4.start()

    t1.join()
    t2.join()
    t3.join()
    t4.join()
    # for i in range(4):
    #     t1 = threading.Thread(target=producer)
    #     t2 = threading.Thread(target=consumer)

    #     t1.start()
    #     t2.start()

    #     t1.join()
    #     t2.join()
    print("---program stoped---")
if __name__ == '__main__':
    # main(len(lis1), '----test----', 20)
    # run_pool2()
    run_semaphore()
